package org.xczy.core.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.xczy.core.common.result.Result;
import org.xczy.core.entity.Role;
import org.xczy.core.service.RoleService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Api("角色模块")
@RestController
@RequestMapping("/role")
public class RoleController {

  @Resource
  private RoleService roleService;

  @ApiOperation("获取角色列表")
  @GetMapping("/list")
  public Result getRoleList(
      @RequestParam(value = "roleName", required = false) String roleName,
      @RequestParam(value = "limit") Long limit,
      @RequestParam(value = "pageSize") Long pageSize
  ){
    LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
    wrapper.like(StringUtils.hasLength(roleName), Role::getRoleName, roleName);
    wrapper.orderByDesc(Role::getRoleId);
    pageSize = pageSize < 5 ? 5 : pageSize < 100 ? pageSize : 100;
    Page<Role> page = new Page<>(limit, pageSize);
    roleService.page(page, wrapper);
    Map<String, Object> map = new HashMap<>();
    map.put("total", page.getTotal());
    map.put("rows", page.getRecords());
    return Result.ok(map);
  }

  @ApiOperation("添加角色")
  @PostMapping("/add")
  public Result addRole(@RequestBody Role role){
    int i = roleService.addRole(role);
    if( i > 0){
      return Result.ok("添加角色成功");
    }
    return Result.fail("添加角色失败");
  }

  @ApiOperation("更新角色")
  @PutMapping("/edit")
  public Result updateRole(@RequestBody Role role){
    int i = roleService.updateRole(role);
    if( i > 0){
      return Result.ok("更新角色成功");
    }
    return Result.fail("更新角色失败");
  }

  @ApiOperation("根据id查询角色")
  @GetMapping("/{id}")
  public Result getRoleById(@PathVariable("id") Integer id) {
    Role role = roleService.getRoleById(id);
    if(role != null){
      return Result.ok(role);
    }
    return Result.fail();
  }

  @ApiOperation("根据id删除角色")
  @DeleteMapping("/{id}")
  public Result deleteRoleById(@PathVariable("id") Integer id) {
    int i = roleService.deleteRoleById(id);
    if( i > 0){
      return Result.ok("删除角色成功");
    }
    return Result.fail("删除角色失败");
  }

}
